package qnb._common.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisCURD {

	private static final JedisPool pool;

	static {
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxIdle(8);
		config.setMinIdle(1);
		pool = new JedisPool(config, "192.168.72.60", 6379, 2000, "12345678");
	}

	public static void main(String args[]) {
//		byte[] b=IOTool.readFile("D:\\tmp\\1.jpg");
//		System.out.println(set("1.jpg".getBytes(), b));
		String str="你好";
		char[] cs=str.toCharArray();
		for(char c:cs) {
			System.out.println(c+0);
		}

		//从redis取出字节
//		byte[] b=get("1.jpg".getBytes());
//		IOTool.writeFile(b, "D:\\tmp\\aaaaaaaaaaaaaaaaaaaaaaaa.jpg");


//		set("abc","aaaaaaaaaaaaa");
//		System.out.println(get("abc"));
//		pool.close();
	}

	/**
	 * 添加一个键值对 到redis数据库
	 *
	 * @param key   键
	 * @param value 值
	 * @return boolean
	 */
	public static boolean set(String key, String value) {
		Jedis jedis = null;
		try {
			jedis = pool.getResource();
			String rs = jedis.set(key, value);
			return rs.equals("OK");
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			if (jedis != null) {
				jedis.close();
			}
		}
	}

	/**
	 * 添加一个键值对 到redis数据库
	 *
	 * @param key   键
	 * @param value 值
	 * @return boolean
	 */
	public static boolean set(byte[] key, byte[] value) {
		Jedis jedis = null;
		try {
			jedis = pool.getResource();
			String rs = jedis.set(key, value);
			return rs.equals("OK");
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			if (jedis != null) {
				jedis.close();
			}
		}
	}

	/**
	 * @param key
	 * @return
	 */
	public static String get(String key) {
		Jedis jedis = null;
		try {
			jedis = pool.getResource();
			return jedis.get(key);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (jedis != null) {
				jedis.close();
			}
		}
	}

	/**
	 * 从redis数据库 取与key相关联的值
	 * @param key
	 * @return
	 */
	public static byte[] get(byte[] key) {
		Jedis jedis = null;
		try {
			jedis = pool.getResource();
			return jedis.get(key);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (jedis != null) {
				jedis.close();
			}
		}
	}

}
